package net 
{
	import binary.QhByteArray;
	/**
	 * socket 二进制数据的缓存读取
	 * @author gcxk721
	 * 2012-3-16 11:09
	 */
	public class QhDataFilter implements IDataFilter 
	{
		/**
		 * 缓存的二进制数组
		 */
		private var m_BuffBytes : QhByteArray;
		
		/**
		 * 截取到完整包之后的处理类
		 */
		private var m_Handler : IMessageHandler;
		
		public function QhDataFilter(handler : IMessageHandler) 
		{
			m_Handler = handler;
			m_BuffBytes = new QhByteArray();
		}
		
		/* INTERFACE net.IDataFilter */
		public function onRecive(bytes : QhByteArray):void 
		{
			m_BuffBytes.writeBytes(bytes, 0, bytes.length);
            m_BuffBytes.position=0;
            while (m_BuffBytes.bytesAvailable > 4)
            {
                var payloadLength : int = m_BuffBytes.readInt();//读取包长
                if (m_BuffBytes.bytesAvailable >= payloadLength + 2)//加上消息头的长度
                 {
					var newMessage : QhByteArray = new QhByteArray();
					m_BuffBytes.readBytes(newMessage, 0, payloadLength + 2);
					m_Handler.onHandler(newMessage);
				}
				else
				{
					m_BuffBytes.position -= 4;
					break;
				}
			}
			var newBuffer : QhByteArray = new QhByteArray();
			newBuffer.writeBytes(m_BuffBytes, m_BuffBytes.position, m_BuffBytes.bytesAvailable);
			m_BuffBytes = newBuffer;
		}
		
	}

}